package com.idbk.chargestation.activity.pile;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.idbk.chargestation.R;
import com.idbk.chargestation.activity.user.ActivityPointCollection;
import com.idbk.chargestation.api.APIForFile;
import com.idbk.chargestation.api.APIForUser;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonHistory;
import com.idbk.chargestation.util.BitmapHelper;
import com.idbk.chargestation.util.CheckUtil;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.view.EToolbar2;
import com.idbk.chargestation.view.FlowRadioGroup;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.callback.Callback;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Response;

/**
 * 充电点采集站点信息<br/>
 * 新增模式：<br/>
 * 修改模式：<br/>
 * @author liangzw,lupc
 *
 */
public class ActivityPointMsg extends AppCompatActivity implements OnClickListener,
OnCheckedChangeListener {

	public final static String TAG = ActivityPointMsg.class.getSimpleName();

	/**
	 * 模式：增加
	 */
	public final static int MODEL_ADD = 0;

	/**
	 * 模式：修改
	 */
	public final static int MODEL_MODIFY = 1;

	public final static String KEY_MODEL = "key_model";


	public final static String[] FILE_NAMES = {
		"point_upload_1.jpg",
		"point_upload_2.jpg",
		"point_upload_3.jpg",
	};

	private Context mContext;

	/**
	 * 当前模式
	 * <br/>
	 * 必须 初始化一种模式
	 */
	private int mModel = -1;

	//充电点名称
	private EditText mEditName;
	//位置信息
	private TextView textLatLng,textProvinceCityCountry;
	private EditText mEditAddress;

	private EditText mEditPhone, mEditNote;//电桩数量,电话,补充说明
	private FlowRadioGroup frgOperators;//运行商
	private RadioGroup rgOpenWay, rgPortType, rgChargeType,rgFree;

	private GridLayout mGridLayout;

	//
	private LinearLayout mLayoutPileInfor;
	private TextView mTextPileInfoTips;

	//慢充、快充、超充 的数据库
	private PileViewGroup mGroupSlow;
	private PileViewGroup mGroupFast;
	private PileViewGroup mGroupSuper;

	/**
	 * 数据
	 */
	private JsonHistory mData;

	private ImageManager mImageManager;	

	protected EToolbar2 mToolbar2;

	private RequestCall mRequest;

	private ProgressDialog mDialog;

	private int[] mSlowIds = {
			R.id.layout_slow_title,//标题栏
			R.id.textview_slow_title,
			R.id.imageview_slow_arrow,

			R.id.layout_slow,//子界面的父容器

			R.id.imageview_slow_del,
			R.id.textview_slow_count,
			R.id.imageview_slow_add,

			R.id.radiogroup_slow_dc_or_ac,
			R.id.radiobutton_slow_dc,
			R.id.radiobutton_slow_ac,

			R.id.edittext_slow_priceinfo,
	};

	private int[] mFastIds = {
			R.id.layout_fast_title,//标题栏
			R.id.textview_fast_title,
			R.id.imageview_fast_arrow,

			R.id.layout_fast,//子界面的父容器

			R.id.imageview_fast_del,
			R.id.textview_fast_count,
			R.id.imageview_fast_add,

			R.id.radiogroup_fast_dc_or_ac,
			R.id.radiobutton_fast_dc,
			R.id.radiobutton_fast_ac,

			R.id.edittext_fast_priceinfo,
	};

	private int[] mSuperIds = {
			R.id.layout_super_title,//标题栏
			R.id.textview_super_title,
			R.id.imageview_super_arrow,

			R.id.layout_super,//子界面的父容器

			R.id.imageview_super_del,
			R.id.textview_super_count,
			R.id.imageview_super_add,

			R.id.radiogroup_super_dc_or_ac,
			R.id.radiobutton_super_dc,
			R.id.radiobutton_super_ac,

			R.id.edittext_super_priceinfo,
	};

	private static class PileViewGroup {
		ViewGroup viewGroupTitle;
		TextView viewTitle;
		ImageView viewArrow;

		TextView textCount;

		EditText viewPriceInfo;//费用信息

		private int mCount = 0;//电桩个数
		private int mPileType = -1;//电桩类型
		//价格信息
		private String getPriceInfo(){
			return viewPriceInfo.getText().toString();
		}

		private PileViewGroup(Activity activity,final int[] ids,int index){
			viewGroupTitle = (ViewGroup)activity.findViewById(ids[0]);
			viewTitle = (TextView)activity.findViewById(ids[1]);

			SpannableString span;
			if(index == 1){
				span = new SpannableString("慢充（功率：1-7kw）"); 
				span.setSpan(new AbsoluteSizeSpan(15,true), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				span.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
				span.setSpan(new AbsoluteSizeSpan(12,true), 2, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 2, 12, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			} else if(index == 2){
				span = new SpannableString("快充（功率：7-50kw）");
				span.setSpan(new AbsoluteSizeSpan(15,true), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				span.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
				span.setSpan(new AbsoluteSizeSpan(12,true), 2, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 2, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			} else {
				span = new SpannableString("超充（功率：大于50kw）");
				span.setSpan(new AbsoluteSizeSpan(15,true), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);	
				span.setSpan(new ForegroundColorSpan(Color.BLACK), 0, 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); 
				span.setSpan(new AbsoluteSizeSpan(12,true), 2, 13, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				span.setSpan(new ForegroundColorSpan(Color.rgb(102, 102, 102)), 2, 13, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
			}
			viewTitle.setText(span);

			viewArrow = (ImageView)activity.findViewById(ids[2]);	
			//子界面			
			final View child =  activity.findViewById(ids[3]);
			viewGroupTitle.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(child.getVisibility() == View.VISIBLE){
						child.setVisibility(View.GONE);
						viewArrow.setImageResource(R.drawable.ico_arrow_n_grey_d);
					} else {
						child.setVisibility(View.VISIBLE);
						viewArrow.setImageResource(R.drawable.ico_arrow_n_grey_u);
					}
				}
			});

			ImageView del = (ImageView)activity.findViewById(ids[4]);
			del.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(mCount <= 0){
						return;
					}
					mCount--;
					String text = mCount + "";
					textCount.setText(text);
				}
			});

			textCount = (TextView)activity.findViewById(ids[5]);
			String text = mCount + "";
			textCount.setText(text);

			ImageView add = (ImageView)activity.findViewById(ids[6]);
			add.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if(mCount > 100){
						return;
					}
					mCount++;
					String text = mCount + "";
					textCount.setText(text);
				}
			});

			RadioGroup radioGroup = (RadioGroup)activity.findViewById(ids[7]);
			radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(RadioGroup group, int checkedId) {
					if(checkedId == ids[8]){
						mPileType = JsonHistory.CHARGE_MODEL_DC;
					} else if(checkedId == ids[9]){
						mPileType = JsonHistory.CHARGE_MODEL_AC;
					}
				}
			});

			//价格信息
			viewPriceInfo = (EditText)activity.findViewById(ids[10]);
		}
	}

	private final static int[] TITLE_ID_ARRAY = {
		R.id.textview_pu_name,
		R.id.textview_pu_address,
		R.id.textview_pu_isopen,
		R.id.textview_pu_port_type,
		R.id.textview_pu_isfree,
		R.id.textview_pu_charge_type,
		R.id.textview_pu_vendor,
		R.id.textview_pu_piles_info,
	};

	private final static String[] TITLE_ARRAY = {
		"充电点名称<font color='#e23e50'> *</font>",
		"位置信息<font color='#e23e50'> *</font>",
		"开放方式<font color='#e23e50'> *</font>",
		"车位类型<font color='#e23e50'> *</font>",
		"是否免费<font color='#e23e50'> *</font>",
		"充电结算方式<font color='#e23e50'> *</font>",
		"运营商<font color='#e23e50'> *</font>",
		"桩位信息<font color='#e23e50'> *</font>",
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_point_msg);

		mContext = this;

		setupView();

		setupData();
	}

	private void setupView() {
		setupToolBar2();

		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

		//初始化 几个必填选项的标题
		for (int i = 0; i < TITLE_ID_ARRAY.length; i++) {
			TextView tv = (TextView)findViewById(TITLE_ID_ARRAY[i]);
			if (tv != null) {
				tv.setText(CheckUtil.textFromHtml(TITLE_ARRAY[i]));
			}
		}

		mLayoutPileInfor = (LinearLayout)findViewById(R.id.layout_pileinfo);
		mTextPileInfoTips = (TextView)findViewById(R.id.layout_tip_1);
		setupPileInfoView();

		//初始化其他

		mEditName = (EditText)findViewById(R.id.edittext_point_name);

		textLatLng = (TextView) findViewById(R.id.textview_lat_lng);
		textProvinceCityCountry = (TextView) findViewById(R.id.textview_province_city_country);
		mEditAddress = (EditText) findViewById(R.id.edittext_address);

		mEditPhone = (EditText) findViewById(R.id.edittext_phone);
		mEditNote = (EditText) findViewById(R.id.edittext_ramark);

		rgOpenWay = (RadioGroup) findViewById(R.id.radio_open_way);
		rgPortType = (RadioGroup) findViewById(R.id.radio_port_type);
		rgChargeType = (RadioGroup) findViewById(R.id.radio_charge_type);

		rgFree = (RadioGroup) findViewById(R.id.radio_charge_free);
		frgOperators = (FlowRadioGroup) findViewById(R.id.operators_radiogroup);
		mGridLayout = (GridLayout) findViewById(R.id.operators_grid);

		rgOpenWay.setOnCheckedChangeListener(this);
		rgPortType.setOnCheckedChangeListener(this);
		rgChargeType.setOnCheckedChangeListener(this);
		rgFree.setOnCheckedChangeListener(this);

		findViewById(R.id.textview_submit).setOnClickListener(this);


		mImageManager = new ImageManager();

		frgOperators.setOnCheckedChangeListener(new FlowRadioGroup.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(FlowRadioGroup group, int checkedId) {
				RadioButton button = (RadioButton) findViewById(group.getCheckedRadioButtonId());
				if (button != null) {
					int vendorId;
					vendorId = Integer.parseInt(button.getTag().toString());
					mData.operatorId = vendorId;
				}
			}
		});
	}

	private void setupToolBar2() {
		mToolbar2 = (EToolbar2) findViewById(R.id.tj_toolbar2);
		mToolbar2.setTitle(getTitle());
		mToolbar2.getBackView().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});	
	}

	private void setupPileInfoView(){
		mGroupSlow = new PileViewGroup(this,mSlowIds,1);
		mGroupFast = new PileViewGroup(this,mFastIds,2);
		mGroupSuper = new PileViewGroup(this,mSuperIds,3);
	}

	private void setupData() {
		Bundle bundle = getIntent().getExtras();
		//判断当前模式
		mModel = bundle.getInt(KEY_MODEL, -1);
		if(mModel < 0){
			Toast.makeText(mContext, "错误：缺少传入参数", Toast.LENGTH_SHORT).show();
			finish();
		} else if(mModel == MODEL_ADD){
			setupAddModel(bundle);
		} else if(mModel == MODEL_MODIFY){
			setupModifyModel(bundle);
		}
	}

	//增加模式
	private void setupAddModel(Bundle bundle){
		//增加模式下 可以添加桩位数据
		mTextPileInfoTips.setVisibility(View.GONE);
		mLayoutPileInfor.setVisibility(View.VISIBLE);

		mData = new JsonHistory();
		mData.address = bundle.getString(ActivityPointCollection.CHARGE_COLLECTION_ADDRESS);
		mData.provinceName = bundle.getString(ActivityPointCollection.CHARGE_COLLECTION_PROVINCE);
		mData.cityName = bundle.getString(ActivityPointCollection.CHARGE_COLLECTION_CITY);
		mData.countyName = bundle.getString(ActivityPointCollection.CHARGE_COLLECTION_COUNTRY);
		mData.lng = bundle.getDouble(ActivityPointCollection.CHARGE_COLLECTION_LNG);
		mData.lat = bundle.getDouble(ActivityPointCollection.CHARGE_COLLECTION_LAT);


		textLatLng.setText(String.format(Locale.CHINA, "纬度：%.6f    经度：%.6f", mData.lat,mData.lng));
		textProvinceCityCountry.setText(mData.provinceName + "  " + mData.cityName + "  " + mData.countyName);
		String str[] = mData.address.split(mData.provinceName + mData.cityName + mData.countyName);
		if(str.length > 1) {
			mEditAddress.setText(str[1]);
		}

		mImageManager.setupData();
	}

	//修改模式
	private void setupModifyModel(Bundle bundle) {
		//修改模式  不允许修改 桩位信息
		mTextPileInfoTips.setVisibility(View.VISIBLE);
		mLayoutPileInfor.setVisibility(View.GONE);

		//接收
		mData = bundle.getParcelable(JsonHistory.KEY);
		if (mData != null) {
			mEditName.setText(mData.name);
			textProvinceCityCountry.setText(mData.provinceName + "  " + mData.cityName + "  " + mData.countyName);
			mEditAddress.setText(mData.address);
			//开放方式
			if(mData.isOpening) {
				((RadioButton)rgOpenWay.getChildAt(0)).setChecked(true);
			} else {
				((RadioButton)rgOpenWay.getChildAt(1)).setChecked(true);
			}
			//车位类型
			if(mData.parkingType == JsonHistory.PARKING_GROUND) {
				((RadioButton)rgPortType.getChildAt(0)).setChecked(true);
			} else {
				((RadioButton)rgPortType.getChildAt(1)).setChecked(true);
			}
			//充电方式
			if(mData.chargeMethod == JsonHistory.CHARGE_METHOD_CARD) {
				((RadioButton)rgChargeType.getChildAt(0)).setChecked(true);
			} else if(mData.chargeMethod == JsonHistory.CHARGE_METHOD_APP) {
				((RadioButton)rgChargeType.getChildAt(1)).setChecked(true);
			} else if(mData.chargeMethod == JsonHistory.CHARGE_METHOD_CARD_AND_APP) {
				((RadioButton)rgChargeType.getChildAt(2)).setChecked(true);
			}
			//是否免费
			if(mData.isFree) {
				((RadioButton)rgFree.getChildAt(0)).setChecked(true);
			} else {
				((RadioButton)rgFree.getChildAt(1)).setChecked(true);
			}
			//运营商
			for (int i = 0; i < mGridLayout.getChildCount(); i++) {
				RadioButton rb = (RadioButton)mGridLayout.getChildAt(i);
				if(rb.getTag().toString().equals(mData.operatorId + "")){
					rb.setChecked(true);
					break;
				}
			}

			//联系电话
			if(mData.contactNum != null){
				mEditPhone.setText(mData.contactNum);
			}
			//备注
			if(mData.notes != null){
				mEditNote.setText(mData.notes);
			}
		}
		//图片
		mImageManager.setupData();
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.textview_submit:
			commit();//提交信息			
			break;
		default:
			break;
		}
	}

	//检查必填信息填写是否完整
	private boolean checkInput() {
		if("".equals(mEditName.getText().toString())){
			Toast.makeText(this, "请填写充电点名称", Toast.LENGTH_SHORT).show();
			return false;
		}
		if("".equals(mEditAddress.getText().toString())) {
			Toast.makeText(this, "请填写位置信息", Toast.LENGTH_SHORT).show();
			return false;
		} 
		else if(rgOpenWay.getCheckedRadioButtonId() == -1) {
			Toast.makeText(this, "请选择开放方式", Toast.LENGTH_SHORT).show();
			return false;
		}
		else if(rgPortType.getCheckedRadioButtonId() == -1) {
			Toast.makeText(this, "请选择车位类型", Toast.LENGTH_SHORT).show();
			return false;
		}
		else if(rgChargeType.getCheckedRadioButtonId() == -1) {
			Toast.makeText(this, "请选择充电结算方式", Toast.LENGTH_SHORT).show();
			return false;
		}
		else if(rgFree.getCheckedRadioButtonId() == -1) {
			Toast.makeText(this, "请选择收费方式", Toast.LENGTH_SHORT).show();
			return false;
		}
		else if(frgOperators.getCheckedRadioButtonId() == -1) {
			Toast.makeText(this, "请选择运营商", Toast.LENGTH_SHORT).show();
			return false;
		}
		if(mModel == MODEL_ADD){
			if(mGroupSlow.mCount < 1 && mGroupFast.mCount < 1 && mGroupSuper.mCount < 1){
				Toast.makeText(this, "你至少需要填写一项桩位信息", Toast.LENGTH_SHORT).show();	
				return false;
			}
			if(mGroupSlow.mCount > 0 && mGroupSlow.mPileType == -1){
				Toast.makeText(this, "慢充信息必须填写完整", Toast.LENGTH_SHORT).show();
				return false;
			}
			if(mGroupFast.mCount > 0 && mGroupFast.mPileType == -1){
				Toast.makeText(this, "快充信息必须填写完整", Toast.LENGTH_SHORT).show();
				return false;
			}
			if(mGroupSuper.mCount > 0 && mGroupSuper.mPileType == -1){
				Toast.makeText(this, "超充信息必须填写完整", Toast.LENGTH_SHORT).show();
				return false;
			}
		}
		return true;
	}

	private void commit() {
		//校验输入
		if(!checkInput()) {
			return;
		}
		//提取数据
		extractData();
		//开始提交
		showMainProgressDialog();

		mRequest = APIForFile.chargeCollection(
				mData,
				mImageManager.getUploadPictureStream(0),
				mImageManager.getUploadPictureStream(1),
				mImageManager.getUploadPictureStream(2),
				new StringCallback() {

					@Override
					public void onResponse(String response, int id) {
						JsonBase result = GsonUtils.toBean(JsonBase.class, response);
						if(BaseActivity.handleResponseStatus(ActivityPointMsg.this,result)){
							BaseActivity.showResult(ActivityPointMsg.this, "提交成功！", true);
						}
					}

					@Override
					public void onError(Call call, Exception e, int id) {
						Snackbar.make(mToolbar2, "提交失败！", Snackbar.LENGTH_LONG)
						.setAction("重试", new OnClickListener() {

							@Override
							public void onClick(View v) {
								commit();
							}
						})
						.show();
					}

					@Override
					public void onAfter(int id) {
						super.onAfter(id);
						dismissMainProgressDialog();
					}

				});
	}

	private void extractData(){
		//必填项-充电点名称
		mData.name = mEditName.getText().toString();
		//必填项-地址
		mData.address = mEditAddress.getText().toString();
		//必填项-开放方式--f
		//必填项-车位类型--f
		//必填项-充电方式--f
		//必填项-是否免费--f
		//必填项-运营商--f

		//只有在增加模式下 才提取 电桩信息
		if(mModel == MODEL_ADD){
			if(mGroupSlow.mCount > 0){
				mData.count4Slow = mGroupSlow.mCount;
				mData.power_Slow = JsonHistory.POWER_DESC_1_7_KW;
				mData.chargeModel_Slow = mGroupSlow.mPileType;
				mData.electricityPriceInfo_Slow = mGroupSlow.getPriceInfo();
			}
			if(mGroupFast.mCount > 0){
				mData.count4Fast = mGroupFast.mCount;
				mData.power_Fast = JsonHistory.POWER_DESC_7_50_KW;
				mData.chargeModel_Fast = mGroupFast.mPileType;
				mData.electricityPriceInfo_Fast = mGroupFast.getPriceInfo();
			}
			if(mGroupSuper.mCount > 0){
				mData.count4Super = mGroupSuper.mCount;
				mData.power_Super = JsonHistory.POWER_DESC_ABOVE_50_KW;
				mData.chargeModel_Super = mGroupSuper.mPileType;
				mData.electricityPriceInfo_Super = mGroupSuper.getPriceInfo();
			}
		}

		//选填项-联系电话
		String phone = mEditPhone.getText().toString();
		if(!"".equals(phone)){
			mData.contactNum = phone;	
		}
		//选填项-备注
		String notes = mEditNote.getText().toString();
		if(!"".equals(notes)){
			mData.notes = notes;	
		}		

		//其他项
		if(mModel == MODEL_ADD){
			mData.isEnable = true;
		}
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		RadioButton button = new RadioButton(this);
		button = (RadioButton) findViewById(group.getCheckedRadioButtonId());
//		String str = button.getText().toString();
		if (button != null) {
			switch(group.getId()) {
				case R.id.radio_open_way: //开放方式
					mData.isOpening = (button.getId() == R.id.radiobutton_isopen_true);
					break;
				case R.id.radio_port_type: //车位类型
					if(button.getId() == R.id.radiobutton_parkingtype_1) {
						mData.parkingType = JsonHistory.PARKING_GROUND;
					} else {
						mData.parkingType = JsonHistory.PARKING_UNDERGROUND;
					}
					break;
				case R.id.radio_charge_type: //充电方式
					if(button.getId() == R.id.radiobutton_chargetype_1) {
						mData.chargeMethod = JsonHistory.CHARGE_METHOD_CARD;
					} else if(button.getId() == R.id.radiobutton_chargetype_2) {
						mData.chargeMethod = JsonHistory.CHARGE_METHOD_APP;
					} else {
						mData.chargeMethod = JsonHistory.CHARGE_METHOD_CARD_AND_APP;
					}
					break;
				case R.id.radio_charge_free: //是否免费
					mData.isFree = (button.getId() == R.id.radiobutton_isfree_1);
					break;
				default:
					break;
			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode != RESULT_OK){
			return;
		}
		if(requestCode >= 1 && requestCode <= 3){
			Uri uri = data.getData();
			mImageManager.finishSelectImage(requestCode,uri);

		}
	}

	private void showMainProgressDialog(){
		if(mDialog != null && mDialog.isShowing()){
			mDialog.dismiss();	
		}
		mDialog = ProgressDialog.show(this, null, "提交中...", true, true, new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				if(mRequest != null){
					mRequest.cancel();
				}
			}
		});
		//点击屏幕外不取消
		mDialog.setCanceledOnTouchOutside(false);
	}

	private void dismissMainProgressDialog(){
		if(mDialog != null){
			mDialog.dismiss();
		}
	}

	private static class MyImageData {

		private Context mContext;
		private int mIndex;

		private Uri nativeUri;

		private int mId;
		private String serverURL;

		private boolean hasImage;
		private boolean shouldUpload;

		private ImageView mImage;
		private ImageView mImageDelete;

		private boolean isServerImage;

		private MyImageData(Context context,int index){
			mContext = context;
			mIndex = index;
			hasImage = false;
			shouldUpload = false;
		}

		private void setNativeUri(Uri uri){
			nativeUri = uri;
			hasImage = true;
			shouldUpload = true;
			isServerImage = false;

			Picasso.with(mContext).load(uri).resize(68,68).into(mImage);
			mImageDelete.setVisibility(View.VISIBLE);
		}

		private void setServerURL(int id,String url){
			mId = id;
			serverURL = url;
			hasImage = true;
			shouldUpload = false;
			isServerImage = true;

			Picasso.with(mContext).load(url).fit().centerInside().into(mImage);
			mImageDelete.setVisibility(View.VISIBLE);
		}

		private void deleteOrRemoveImage(){
			if(isServerImage){
				//
				String msg = "你确定要删除该图片吗？<br/><font color='red'>注意：点击确定后即使不提交其他修改也会删除该图片！</font>";
				new AlertDialog.Builder(mContext)
				.setMessage(CheckUtil.textFromHtml(msg))
				.setNegativeButton(R.string.common_cancel, null)
				.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						serverURL = null;
						hasImage = false;
						shouldUpload = false;
						isServerImage = false;
						APIForUser.deletePointCollectionImage(mId, mIndex, new Callback<String>(	) {
							
							@Override
							public String parseNetworkResponse(Response response, int id)
									throws Exception {
								return null;
							}
							
							@Override
							public void onResponse(String response, int id) {
							}
							
							@Override
							public void onError(Call call, Exception e, int id) {
							}
						});
						mImage.setImageResource(R.drawable.image_add_selector);
						mImageDelete.setVisibility(View.GONE);
					}
				})
				.create()
				.show();				
			} else {
				//
				nativeUri = null;
				hasImage = false;
				shouldUpload = false;
				isServerImage = false;
				mImage.setImageResource(R.drawable.image_add_selector);
				mImageDelete.setVisibility(View.GONE);
			}
		}
	}

	private class ImageManager implements OnClickListener{

		private final MyImageData[] mImageDatas = new MyImageData[3];

		int[] imageIds = {
				R.id.image_point_pic1,
				R.id.image_point_pic2,
				R.id.image_point_pic3,
		};

		int[] imageDeleteIds = {
				R.id.imageview_delete_1,
				R.id.imageview_delete_2,
				R.id.imageview_delete_3,
		};

		private ImageManager(){
			for (int i = 0; i < 3; i++) {
				MyImageData item = new MyImageData(mContext,i+1);
				item.mImage = (ImageView)findViewById(imageIds[i]);
				if (item.mImage != null) {
					item.mImage.setOnClickListener(ImageManager.this);
				}

				item.mImageDelete = (ImageView)findViewById(imageDeleteIds[i]);
				if (item.mImageDelete != null) {
					item.mImageDelete.setOnClickListener(ImageManager.this);
					item.mImageDelete.setVisibility(View.GONE);
				}

				mImageDatas[i] = item;
			}
		}

		public void setupData(){
			if(mModel == MODEL_ADD){
				//此时不用做什么
			} else {
				if(mData.imageURL != null && mData.imageURL.size() > 0){				
					for (int i = 0; i < mData.imageURL.size(); i++) {
						if(mData.imageURL.get(i) == null ||
								"".equals(mData.imageURL.get(i)) ||
								mData.imageURL.get(i).length() < 3){
							continue;
						}
						String url = ChargeStationURL.getAbsoluteApiUrlFromRoot(mData.imageURL.get(i));
						mImageDatas[i].setServerURL(mData.id,url);
					}
				} else {
					setupImage();
				}
			}
		}

		private void setupImage(){

		}

		private void finishSelectImage(int index,Uri uri){
			mImageDatas[index - 1].setNativeUri(uri);			
		}

		@Override
		public void onClick(View v) {
			if(v.getId() == imageIds[0]){
				pickOrDisplayImage(1);
			} else if(v.getId() == imageIds[1]){
				pickOrDisplayImage(2);
			} else if(v.getId() == imageIds[2]){
				pickOrDisplayImage(3);
			} else if(v.getId() == imageDeleteIds[0]){
				mImageDatas[0].deleteOrRemoveImage();			
			} else if(v.getId() == imageDeleteIds[1]){
				mImageDatas[1].deleteOrRemoveImage();
			} else if(v.getId() == imageDeleteIds[2]){
				mImageDatas[2].deleteOrRemoveImage();
			}
		}

		private void pickOrDisplayImage(int index){
			if(mImageDatas[index - 1].hasImage){
				//此时显示图片
				Log.d(TAG, "pickOrDisplayImage: index :" + index);


			} else {
				//此时选择图片				
				Intent intent = new Intent(Intent.ACTION_PICK,
						Images.Media.EXTERNAL_CONTENT_URI);			
				intent.setType("image/*");
				startActivityForResult(Intent.createChooser(intent, "选择图片"),index);
			}			
		}

		private File getUploadPictureStream(int position){
			if(!mImageDatas[position].hasImage || !mImageDatas[position].shouldUpload){
				return null;
			}
			Uri uri = mImageDatas[position].nativeUri;
			if(uri != null){
				//将uri转化为 压缩后的图片
				File input = BitmapHelper.getFileFromUri(mContext,uri);
				int size = BitmapHelper.getFileSize(input);
				if(size == 0){
					//表示路径有问题
					Log.e(TAG, "选择的照片路径错误，无法获取文件大小");
					return null;
				} else if(size <= JsonHistory.IMAGE_SIZI_LIMIT){
					return input;
				} else {
					//此时需要压缩上传
					File output = new File(getExternalFilesDir(null),FILE_NAMES[position]);
					BitmapHelper.compressBitmap(input,output);
					return output;
				}
			} else {
				return null;
			}
		}

	}

}
